package top.jacktgq.lock.jmm.visibility;

import top.jacktgq.utils.LogUtils;
import top.jacktgq.utils.Sleeper;

/**
 * 
 * @Title: VisibilityDemo.java 
 * @Package top.jacktgq.lock.jmm.visibility 
 * @Description: java内存模型之可见性
 * @author CandyWall   
 * @date 2020年11月2日 下午2:55:12 
 * @version V1.0
 */
public class VisibilityProblem_Solve2 {
	private static boolean isRunning = true;
	private static Object lock = new Object();
	
	public static void main(String[] args) {
		Thread t = new Thread(() -> {
			while(true) {
				//将共享变量放到同步块内，也可以解决内存的可见性问题，
				//不过synchronized和volatile相比属于重量级操作，性能不如volatile高
				synchronized (lock) {
					if(!isRunning) {
						break;
					}
				}
			}
		});
		t.start();
		
		Sleeper.sleep(1);
		
		LogUtils.log("VisibilityDemo1", "停止t线程");
		//线程t不会如预想的停下来
		//synchronized (lock) {
			isRunning = false;
		//}
	}
}
